package com.csii.adhoc.util;

import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class BeanCreater {

    public static Object generateObject(Map map) {
        BeanGenerator generator = new BeanGenerator();
        Set keySet = map.keySet();
        for (Iterator i = keySet.iterator(); i.hasNext(); ) {
            String key = (String) i.next();
            Class<?> aClass = Object.class;
            try {
                aClass = map.get(key) != null ? Class.forName(map.get(key).getClass().getName()) : Object.class;
            } catch (ClassNotFoundException e) {
            }
            generator.addProperty(key, aClass);
        }
        return generator.create();
    }

    public static Object generateAndSetObject(Map map){
        Object obj = generateObject(map);
        Set set = map.keySet();
        for (Object o : set) {
            String key=(String)o;
            Object value = map.get(o);
            setValue(obj,key,value);
        }
        return obj;
    }

    public static Object getValue(Object obj, String property) {
        BeanMap beanMap = BeanMap.create(obj);
        return beanMap.get(property);
    }

    public static void setValue(Object obj, String property, Object value) {
        BeanMap beanMap = BeanMap.create(obj);
        beanMap.put(property, value);
    }
}
